<template>
  <el-tabs v-model="activeName" style="height: 370px" @tab-click="handleClick">
    <el-tab-pane
      v-for="(field, index) in props.result"
      :key="index"
      :label="field.name"
      :name="field.type"
    >
      <el-table
        height="300px"
        v-el-table-infinite-scroll="load"
        :data="tableData"
        :infinite-scroll-disabled="disabled"
      >
        <el-table-column v-if="field.expand" type="expand" v-slot="{ row }">
          <el-table
            :data="row.vulnBugInfo"
            border
            style="width: 95%; margin-left: auto; margin-right: 0"
          >
            <el-table-column
              v-if="field.subCon.type === 'table'"
              align="center"
              fixed
              v-for="(subField, index) in field.subCon.columns"
              :prop="subField.name"
              :key="index"
              :label="subField.comment"
              :sortable="subField.name === 'level'"
              :sort-method="customSortLevelMethod"
            >
            </el-table-column>
          </el-table>
        </el-table-column>
        <el-table-column
          align="center"
          v-for="(fieldDetail, index) in field.columns"
          :key="index"
          :prop="fieldDetail.name"
          :label="fieldDetail.comment"
        >
          <el-table-column
            v-if="fieldDetail.type === 'table'"
            v-for="(subFieldDetail, index) in fieldDetail.columns"
            :key="index"
            :prop="subFieldDetail.name"
            :label="subFieldDetail.comment"
          />
        </el-table-column>
        <el-table-column
          align="center"
          v-if="field.expand"
          label="漏洞数"
          width="300px"
          v-slot="{ row }"
        >
          总数: {{ row.vulnBugInfo ? row.vulnBugInfo.length : 0 }}
          <span style="">
            低:
            {{
              row.vulnBugInfo
                ? row.vulnBugInfo.filter(item => item.level === '低危').length
                : 0
            }}</span
          >
          <span style="color: #e6a23c">
            中:
            {{
              row.vulnBugInfo
                ? row.vulnBugInfo.filter(item => item.level === '中危').length
                : 0
            }}</span
          >
          <span style="color: red">
            高:
            {{
              row.vulnBugInfo
                ? row.vulnBugInfo.filter(item => item.level === '高危').length
                : 0
            }}</span
          >
        </el-table-column>
        <el-table-column
          v-if="field.operations"
          align="center"
          label="操作"
          width="120"
        >
          <template #default="scope">
            <el-button
              v-for="(operationetail, index) in field.operations"
              :key="index"
              link
              :type="operationetail.styleType"
              size="small"
              @click="handleOperationetail(operationetail.type)"
              >{{ operationetail.comment }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <p v-if="loading" class="textCenter">加载中...</p>
      <p v-if="noMore" class="textCenter">到底了</p>
    </el-tab-pane>
  </el-tabs>
</template>

<script lang="ts" setup>
import { onMounted, computed, onUnmounted, reactive, ref, watch } from 'vue';
import { toolDebugResult } from '@/api/topo/tools';
import { default as vElTableInfiniteScroll } from 'el-table-infinite-scroll';

import type { TabsPaneContext } from 'element-plus';
import axios from 'axios';
import { ElMessage } from 'element-plus'; // 引入axios

const activeName = ref('');
const loading = ref(false);
const startID = ref(null);
const endID = ref(null);
const noMore = ref(false);
const disabled = computed(() => loading.value || noMore.value);
const tableData = ref([]);

let timerId;

const props = defineProps<{
  id?: number;
  taskID?: number;
  status?: number;
  result?: Record<string, any>;
}>();

// tab
const handleClick = (tab: TabsPaneContext, event: Event) => {
  startID.value = 0;
  endID.value = 0;
  tableData.value = [];
  getToolDebugResult(tab.props.name);
};

// 按钮
const handleOperationetail = async type => {
  if (type === 'download') {
    try {
      const downloadLink = document.createElement('a');
      downloadLink.setAttribute('download', '');
      downloadLink.href =
        '/api/topo/simulation/research/task/' + props.taskID + '/file/'; // 创建下载链接
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
      ElMessage.success('下载中');
    } catch (error) {
      ElMessage.error('下载失败');
    }
  }
};

const load = () => {
  loading.value = true;
  setTimeout(() => {
    toolDebugResult(props.id, {
      num: 5,
      endID: endID.value,
      resultType: 1,
      toolTaskID: props.taskID,
    }).then(res => {
      // 返回数据为空
      if (res.data.length < 5) {
        noMore.value = true;
      }
      res.data.forEach(result => {
        if (result.result) {
          tableData.value.push(JSON.parse(result.result));
        }
        endID.value = res.data[res.data.length - 1].ID;
      });
    });
    loading.value = false;
  }, 500);
};

const getToolDebugResult = async label => {
  noMore.value = false;
  activeName.value = label;
  if (label === 0) {
    activeName.value = props.result[0].type;
  }
  const { data } = await toolDebugResult(props.id, {
    num: 5,
    resultType: 1,
    toolTaskID: props.taskID,
  });
  data.forEach(result => {
    if (result.result) {
      tableData.value.push(JSON.parse(result.result));
      endID.value = data[data.length - 1].ID;
    }
  });
  startID.value = 0;
  if (data.length > 0) {
    startID.value = data[0].ID;
  }
  if (data.length <= 5) {
    loading.value = false;
  }
  if (props.status === 1) {
    startResult();
  }
};

const customSortLevelMethod = (a, b) => {
  // 定义排序规则，将 '低等' 排在前面，'中等' 排在中间，'高级' 排在后面
  const levelOrder = { 低危: 1, 中危: 2, 高危: 3 };
  return levelOrder[a.level] - levelOrder[b.level];
};

const startResult = () => {
  // 检查是否已经存在定时任务
  if (!timerId) {
    timerId = setInterval(() => {
      getResult();
    }, 2000);
  }
};

const getResult = () => {
  toolDebugResult(props.id, {
    num: 5,
    startID: startID.value,
    resultType: 1,
    toolTaskID: props.taskID,
  }).then(res => {
    res.data.forEach(result => {
      if (startID.value < res.data[0].ID) {
        startID.value = res.data[0].ID;
        if (result.result) {
          tableData.value.unshift(JSON.parse(result.result));
        }
      }
    });
  });
};

const stopResult = () => {
  // 检查是否存在定时任务，然后清除
  if (timerId) {
    clearInterval(timerId);
    timerId = null;
  }
};

onMounted(() => {
  tableData.value = [];
  getToolDebugResult(0);
});

onUnmounted(async () => {
  // 清除定时任务
  stopResult();
});

// 使用watch监听props中status的变化

watch(
  () => props.status,
  (newVal, oldVal) => {
    if (newVal != 1) {
      // 清除定时任务
      stopResult();
      getResult();
    } else {
      tableData.value = [];
      startResult();
    }
  },
);
</script>

<style lang="scss" scoped>
.infinite-list-wrapper {
  display: flex;
  width: 100%;
  height: 350px;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.infinite-list-wrapper p {
  position: absolute;
  bottom: 0;
  left: 50%;
}
.textCenter {
  text-align: center;
  padding-top: 10px;
}
</style>
